{% extends "base.html" %}

{% block title %}学生列表 - 学生管理系统{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="fas fa-users me-2"></i>学生列表</h2>
    <div class="btn-group" role="group">
        <a href="{{ url_for('add_student') }}" class="btn btn-primary">
            <i class="fas fa-plus me-1"></i>添加学生
        </a>
        <a href="{{ url_for('import_students') }}" class="btn btn-outline-info">
            <i class="fas fa-file-import me-1"></i>导入
        </a>
        <a href="/export/excel" class="btn btn-outline-success">
            <i class="fas fa-download me-1"></i>导出
        </a>
    </div>
</div>

<!-- 搜索框 -->
<div class="card mb-4">
    <div class="card-body">
        <form id="searchForm" class="row g-3">
            <div class="col-md-8">
                <input type="text" class="form-control" id="searchInput" 
                       placeholder="搜索学生姓名、专业、年级或邮箱..." name="q">
            </div>
            <div class="col-md-4">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-search me-1"></i>搜索
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 动态字段提示 -->
<div class="alert alert-info mb-3">
    <i class="fas fa-info-circle me-2"></i>
    支持动态字段显示，点击学生行查看完整信息（包括所有自定义字段）
</div>

{% if students %}
    <!-- 桌面端表格 -->
    <div class="d-none d-md-block">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead class="table-light">
                    <tr>
                        <th>姓名</th>
                        <th>年龄</th>
                        <th>性别</th>
                        <th>年级</th>
                        <th>专业</th>
                        <th>邮箱</th>
                        <th>电话</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for student in students %}
                    <tr>
                        <td>{{ student.name }}</td>
                        <td>{{ student.age }}</td>
                        <td>
                            {% if student.gender == 'male' %}
                                男
                            {% elif student.gender == 'female' %}
                                女
                            {% else %}
                                {{ student.gender or '未设置' }}
                            {% endif %}
                        </td>
                        <td>{{ student.grade or '未设置' }}</td>
                        <td>{{ student.major or '未设置' }}</td>
                        <td>
                            {% if student.email %}
                                <a href="mailto:{{ student.email }}">{{ student.email }}</a>
                            {% else %}
                                未设置
                            {% endif %}
                        </td>
                        <td>{{ student.phone or '未设置' }}</td>
                        <td>
                            <div class="btn-group" role="group">
                                <button type="button" 
                                        class="btn btn-sm btn-outline-info btn-action"
                                        title="查看详情"
                                        onclick="showStudentDetail('{{ student._id }}')">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <a href="{{ url_for('edit_student', student_id=student._id) }}" 
                                   class="btn btn-sm btn-outline-primary btn-action"
                                   title="编辑">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <button type="button" 
                                        class="btn btn-sm btn-outline-danger btn-action"
                                        title="删除"
                                        onclick="confirmDelete('{{ student._id }}', '{{ student.name }}')">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>

    <!-- 手机端卡片列表 -->
    <div class="d-md-none">
        {% for student in students %}
        <div class="card mb-3">
            <div class="card-body">
                <h6 class="card-title d-flex justify-content-between align-items-center">
                    {{ student.name }}
                    <span class="badge bg-primary">{{ student.age }}岁</span>
                </h6>
                <div class="row">
                    <div class="col-6">
                        <small class="text-muted">性别:</small>
                        <div>
                            {% if student.gender == 'male' %}
                                男
                            {% elif student.gender == 'female' %}
                                女
                            {% else %}
                                {{ student.gender or '未设置' }}
                            {% endif %}
                        </div>
                    </div>
                    <div class="col-6">
                        <small class="text-muted">年级:</small>
                        <div>{{ student.grade or '未设置' }}</div>
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-12">
                        <small class="text-muted">专业:</small>
                        <div>{{ student.major or '未设置' }}</div>
                    </div>
                </div>
                {% if student.email %}
                <div class="row mt-2">
                    <div class="col-12">
                        <small class="text-muted">邮箱:</small>
                        <div><a href="mailto:{{ student.email }}">{{ student.email }}</a></div>
                    </div>
                </div>
                {% endif %}
                {% if student.phone %}
                <div class="row mt-2">
                    <div class="col-12">
                        <small class="text-muted">电话:</small>
                        <div>{{ student.phone }}</div>
                    </div>
                </div>
                {% endif %}
                <div class="d-flex justify-content-end mt-3 gap-2">
                    <button type="button" 
                            class="btn btn-sm btn-outline-info"
                            title="查看详情"
                            onclick="showStudentDetail('{{ student._id }}')">
                        <i class="fas fa-eye"></i>
                    </button>
                    <a href="{{ url_for('edit_student', student_id=student._id) }}" 
                       class="btn btn-sm btn-outline-primary"
                       title="编辑">
                        <i class="fas fa-edit"></i>
                    </a>
                    <button type="button" 
                            class="btn btn-sm btn-outline-danger"
                            title="删除"
                            onclick="confirmDelete('{{ student._id }}', '{{ student.name }}')">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    
    <div class="d-flex justify-content-between align-items-center mt-3">
        <small class="text-muted">共 {{ students|length }} 名学生</small>
        <div>
            <a href="{{ url_for('statistics') }}" class="btn btn-sm btn-outline-info me-2">
                <i class="fas fa-chart-bar me-1"></i>查看统计
            </a>
            <a href="{{ url_for('api_students') }}" class="btn btn-sm btn-outline-secondary">
                <i class="fas fa-download me-1"></i>导出数据
            </a>
        </div>
    </div>
{% else %}
    <div class="text-center py-5">
        <i class="fas fa-user-graduate fa-4x text-muted mb-3"></i>
        <h4 class="text-muted">暂无学生数据</h4>
        <p class="text-muted">点击右上角按钮添加第一个学生</p>
        <a href="{{ url_for('add_student') }}" class="btn btn-primary mt-2">
            <i class="fas fa-plus me-1"></i>添加学生
        </a>
    </div>
{% endif %}

<!-- 学生详情模态框 -->
<div class="modal fade" id="studentDetailModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">学生详细信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="studentDetailContent">
                    <!-- 动态内容将通过JavaScript填充 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
function confirmDelete(studentId, studentName) {
    if (confirm(`确定要删除学生 "${studentName}" 吗？此操作不可撤销。`)) {
        window.location.href = `/delete/${studentId}`;
    }
}

// 显示学生详情
function showStudentDetail(studentId) {
    console.log('获取学生详情:', studentId);
    
    // 通过API获取学生详情
    fetch(`/api/students/${studentId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(student => {
            console.log('学生详情数据:', student);
            
            // 构建详情内容
            let content = '<div class="row">';
            
            // 排除系统字段
            const excludeFields = ['_id', 'created_at', 'updated_at'];
            
            // 显示所有字段
            Object.entries(student).forEach(([field, value]) => {
                if (!excludeFields.includes(field)) {
                    content += `
                        <div class="col-md-6 mb-2">
                            <strong>${field}:</strong> ${value || '未设置'}
                        </div>
                    `;
                }
            });
            
            content += '</div>';
            
            // 更新模态框内容
            document.getElementById('studentDetailContent').innerHTML = content;
            
            // 显示模态框
            const modalElement = document.getElementById('studentDetailModal');
            if (modalElement) {
                const modal = new bootstrap.Modal(modalElement);
                modal.show();
            } else {
                console.error('模态框元素未找到');
                alert('页面加载异常，请刷新页面后重试');
            }
        })
        .catch(error => {
            console.error('获取学生详情失败:', error);
            alert('获取学生详情失败: ' + error.message);
        });
}

// 搜索功能
document.getElementById('searchForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const query = document.getElementById('searchInput').value.trim();
    
    if (query) {
        // 使用AJAX搜索
        fetch(`/search?q=${encodeURIComponent(query)}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert(data.error);
                    return;
                }
                
                // 这里可以添加搜索结果的显示逻辑
                // 由于时间关系，暂时使用alert提示
                alert(`找到 ${data.total} 条结果`);
                
                // 在实际应用中，这里应该更新页面显示搜索结果
                console.log('搜索结果:', data);
            })
            .catch(error => {
                console.error('搜索失败:', error);
                alert('搜索失败，请重试');
            });
    } else {
        // 清空搜索，重新加载页面
        window.location.reload();
    }
});
</script>
{% endblock %}
